import SwiftUI
import RealityKit
import ARKit

struct DistributionRoomView: View {
    @State private var temperature: Double = 25.0
    @State private var humidity: Double = 60.0
    @State private var modelEntity: Entity?
    @State private var isAlternateCamera = false
    
    @State private var selectedEntityName: String = ""
    @State private var showEntityPanel = false
    @State private var entityScreenPosition: CGPoint = .zero
    
    @EnvironmentObject var appModel: AppModel

    var body: some View {
        ZStack {
            // 3D 模型视图
            RealityView { content in
                do {
                    /// 加载配电箱模型
                    let model = try await Entity.load(named: "distributionRoom")
                    let modelScale: Float = 0.1
                    model.scale = SIMD3<Float>(modelScale, modelScale, modelScale)
                    model.position = SIMD3<Float>(0.05, -0.2, 0.1)

                    // 添加定向光源
                    let directionalLight = DirectionalLight()
                    directionalLight.light.intensity = 2500
                    directionalLight.look(at: [0, 0, 0], from: [1, 2, 2], relativeTo: nil)
                    content.add(directionalLight)

                    model.generateCollisionShapes(recursive: true)
                    debugCollisionStatus(for: model)
                    printEntityHierarchy(model)
                    
                    model.components.set(InputTargetComponent(allowedInputTypes: .indirect))
                    
                    self.modelEntity = model
                    content.add(model)
                    
                    rotateModel(axis: [0, 1, 0])
                    rotateModel10(axis: [1, 0, 0])
                                        
                } catch {
                    print("Error loading model: \(error)")
                }
            }
            .gesture(
                SpatialTapGesture()
                    .targetedToAnyEntity()
                    .onEnded { value in
                        handleEntityTap(value.entity)
                    }
            )
            
            VStack {
                VStack(spacing: 0) {
                    // 添加警告面板点击事件
                    WarningPanelView3()
                        .padding(.top, 80)
                        .onTapGesture {
                            isAlternateCamera.toggle()
                            applyCameraTransition()
                            print("点击了 WarningPanelView3")
                        }
                    
//                    RotationButton(axis: .x) {
////                        rotateModel(axis: [1, 0, 0])
//                        isAlternateCamera.toggle()
//                        applyCameraTransition()
//                        print("点击了 WarningPanelView3")
//                    }
//                    .padding(.top, 80)
                    

                    Image("tri")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 20, height: 20)
                        .padding(.top, 3)
                }
                
                Spacer()
            }
            
            // 信息面板
            if showEntityPanel {
                EquipmentStatusView(onDismiss: {
                    showEntityPanel.toggle()
                })
                .padding(.leading, 180)
            }
            
            // 控制按钮布局
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    ToggleButton(action: {
                        withAnimation {
                            appModel.currentTestView = .park
                        }
                    })
                    .padding(30)
                    .offset(x: -100, y: -220)
                }
            }
        }
    }
    
    // MARK: - 视角切换逻辑
    private func applyCameraTransition() {
        guard let model = modelEntity else { return }
        
        // 设置目标参数
        let targetScale: SIMD3<Float> = isAlternateCamera ? [0.3, 0.3, 0.3] : [0.1, 0.1, 0.1]
        let targetPosition = isAlternateCamera ?
            SIMD3<Float>(0.0, -0.2, 0.2) :
            SIMD3<Float>(0.05, -0.2, 0.1)
        
        // 创建新的变换
        var transform = model.transform
        transform.scale = targetScale
        transform.translation = targetPosition
        
        let radians = isAlternateCamera ? -Float(30).degreesToRadians : Float(30).degreesToRadians
        let aaa: SIMD3<Float> = [1, 0, 0]
        let rotation = simd_quatf(angle: radians, axis: aaa.normalized)
        transform.rotation = rotation * model.transform.rotation

        
        // 执行动画过渡
        model.move(
            to: transform,
            relativeTo: model.parent,
            duration: 0.8,
            timingFunction: .easeInOut
        )
    }

    // MARK: - 实体点击处理
    private func handleEntityTap(_ entity: Entity) {
        print("🎯 点击实体: \(entity.name)")
        entityScreenPosition = CGPoint(x: 600, y: 230)
        addClickEffect(to: entity)
        
        if entity.name == "shebei_504" {
            selectedEntityName = entity.name
            showEntityPanel.toggle()
        }
    }

    // MARK: - 模型操作方法
    private func rotateModel(axis: SIMD3<Float>) {
        guard let model = modelEntity else { return }
        let radians = -Float(90).degreesToRadians
        let rotation = simd_quatf(angle: radians, axis: axis.normalized)
        model.transform.rotation = rotation * model.transform.rotation
    }
    
    private func rotateModel10(axis: SIMD3<Float>) {
        guard let model = modelEntity else { return }
        let radians = Float(30).degreesToRadians
        let rotation = simd_quatf(angle: radians, axis: axis.normalized)
        model.transform.rotation = rotation * model.transform.rotation
    }
    
    private func rotateModel30(axis: SIMD3<Float>) {
        guard let model = modelEntity else { return }
        let radians = -Float(30).degreesToRadians
        let rotation = simd_quatf(angle: radians, axis: axis.normalized)
        model.transform.rotation = rotation * model.transform.rotation
    }
    

    // MARK: - 辅助方法
    private func addClickEffect(to entity: Entity) {
        let highlight = ModelEntity(
            mesh: .generateSphere(radius: 0.01),
            materials: [SimpleMaterial(color: .red, isMetallic: true)]
        )
        highlight.name = "CLICK_HIGHLIGHT"
        entity.addChild(highlight)
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            highlight.removeFromParent()
        }
    }
    
    private func printEntityHierarchy(_ entity: Entity, depth: Int = 0) {
        let indent = String(repeating: "  ", count: depth)
        print("\(indent)🌳 \(entity.name)")
        print("\(indent)   ├─ 子实体数量: \(entity.children.count)")
        print("\(indent)   ├─ 位置: \(entity.position)")
        print("\(indent)   └─ 碰撞体积: \(entity.components[CollisionComponent.self] != nil ? "✅" : "❌")")
        
        // 简化条件判断
        if ["shebei_504"].contains(entity.name) {
            addSimpleBorder(to: entity)
        }
        
        entity.children.enumerated().forEach { index, child in
            printEntityHierarchy(child, depth: depth + 1)
        }
    }
    
    private func addSimpleBorder(to entity: Entity) {
        guard let originalModel = entity.components[ModelComponent.self] else { return }
        
        // 创建边框实体
        let borderEntity = Entity()
        var borderModel = originalModel
        
        // 使用更鲜艳的半透明红色材质
        let borderMaterial = SimpleMaterial(
            color: .red.withAlphaComponent(1), // 增加不透明度
            isMetallic: false
        )
        
        borderModel.materials = [borderMaterial]
        borderEntity.components.set(borderModel)
        
        // 加大缩放比例（根据需求调整）
        let scaleFactor: Float = 1.05 // 从 1.02 增加到 1.05（5%）
        borderEntity.scale = SIMD3<Float>(
            repeating: scaleFactor
        )
        
        // 将边框实体作为子实体添加
        entity.addChild(borderEntity)
        
        // 生成原实体的碰撞体
        entity.generateCollisionShapes(recursive: true)
    }
    
    private func printChildRecursive(_ entity: Entity, depth: Int, isLast: Bool) {
        let indent = String(repeating: "   ", count: depth)
        let connector = isLast ? "└─" : "├─"
        
        for (index, child) in entity.children.enumerated() {
            let isChildLast = index == entity.children.count - 1
            print("\(indent)\(connector) 子实体 \(index + 1): \(child.name)")
            printChildRecursive(child, depth: depth + 1, isLast: isChildLast)
        }
    }
    
    private func debugCollisionStatus(for entity: Entity) {
        var collisionCount = 0
        func countCollision(_ entity: Entity) {
            if entity.components[CollisionComponent.self] != nil {
                collisionCount += 1
            }
            entity.children.forEach(countCollision)
        }
        countCollision(entity)
    }
}
